package com.jic.point.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.PageResult;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.exception.AppRuntimeException;
import com.jic.point.mapper.ConfPlatformMapper;
import com.jic.point.mapper.ConfPointCardBatchMapper;
import com.jic.point.mapper.ConfPointCardMapper;
import com.jic.point.model.entity.ConfPointCardBatch;
import com.jic.point.model.vo.request.ConfPointCardBatchRequest;
import com.jic.point.model.vo.request.QuantityRequest;
import com.jic.point.model.vo.response.ConfPointCardBatchResponse;
import com.jic.point.service.ConfPointCardBatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

//import net.sf.jsqlparser.statement.Commit;

/**
 * 接口实现类
 *
 * @author : tzc
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class ConfPointCardBatchServiceImpl implements ConfPointCardBatchService {

    @Resource
    private ConfPointCardBatchMapper mapper;

    @Resource
    private ConfPointCardMapper cardMapper;

    @Resource
    private ConfPlatformMapper confPlatformMapper;


    /**
     * 新增记录
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    public int save(ConfPointCardBatch request) {
        int flag = mapper.insert(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }
    }


    /**
     * 保存或修改记录信息
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存或修改成功
     * author tzc
     * @date 2020-3-11 20:54:09
     */
    @Override
    public int saveOrUpdate(ConfPointCardBatch request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKey(request);
                if (flag == 1) {
                    return 1;
                }
            } else {
                log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.insertSelective(request);
                if (flag == 1) {
                    return 1;
                } else {
                    throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改失败");
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "用户保存或修改失败");
        }
        return -1;
    }


    /**
     * 删除记录
     *
     * @param request 需要删除,含有主键的入参实体类
     * @return int 是否删除成功
     */
    @Override
    public int deleteByPrimaryKey(ConfPointCardBatch request) {
        int flag = mapper.deleteByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
        }
    }


    /**
     * 逻辑删除记录
     *
     * @param request 含有主键的逻辑删除实体类
     * @return int 是否逻辑删除成功
     */
    @Override
    public int deleteByPrimaryKeyLogically(ConfPointCardBatch request) {
        request.setDeleteFlag(1);
        int flag = mapper.deleteByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
        }
    }


    /**
     * 修改
     *
     * @param request
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(ConfPointCardBatch request) {
        try {
            log.info("修改记录");
            ConfPointCardBatch param = new ConfPointCardBatch();
            BeanUtils.copyProperties(request, param);
            param.setTotalPoint(param.getTotalNum().multiply(param.getPointCardLimit()));
            int flag = mapper.updateByPrimaryKeySelective(param);
            if (flag == 1) {
                return 1;
            } else {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
            }
        } catch (Exception e) {
            log.error("修改记录失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
        }

    }

    /**
     * 记录详情
     *
     * @param request 查询的入参实体类
     * @return 数据库查询到的实体类
     */
    @Override
    public ConfPointCardBatch getByPrimaryKey(ConfPointCardBatch request) {
        return mapper.selectByPrimaryKey(request);
    }


    /**
     * 分页查询
     *
     * @param request 分页查询入参实体类
     * @return 含有分页信息的实体类列表
     */
    @Override
    public PageInfo<ConfPointCardBatchResponse> listPageBySelective(ConfPointCardBatchRequest request, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        request.setDeleteFlag(0);
        if (request.getExpiration() != null && request.getExpiration().size() > 1) {
            request.setMinExpiration(request.getExpiration().get(0));
            request.setExpiryTime(request.getExpiration().get(1));
        }
        List<ConfPointCardBatch> list = mapper.listPageBySelective(request);
        List<ConfPointCardBatchResponse> collect = list.stream().map(item -> {
            ConfPointCardBatchResponse confPointCardBatchResponse = new ConfPointCardBatchResponse();
            BeanUtils.copyProperties(item, confPointCardBatchResponse);
            confPointCardBatchResponse.setQuantity(JSONObject.parseArray(item.getQuantity(), QuantityRequest.class));
            return confPointCardBatchResponse;
        }).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo(collect);
        PageResult<ConfPointCardBatchResponse> result = new PageResult<>();
        result.setTotal(pageInfo.getTotal());
        result.setRows(collect);
        return new PageInfo(collect);
    }

    /**
     * 不分页查询
     *
     * @param request 不分页查询入参实体类
     * @return 数据库查到的实体类列表
     */
    @Override
    public List<ConfPointCardBatch> listAllRecord(ConfPointCardBatch request) {
        //分页处理
        request.setDeleteFlag(0);
        return mapper.selectBySelective(request);
    }

    /**
     * @description: 释放积分
     * @return:
     * @author: fengrui
     * @time: 2020/11/27 15:07
     */
    @Override
    @Transactional
    public Integer releasePointCart(List<String> releaseBatch) {
        log.error("释放积分开始，参数："+releaseBatch.toString());
        Integer result = mapper.releasePointCart(releaseBatch);
        int returnValue = 0;
        if (result > 0) {
            releaseBatch.stream().map(item -> {
                ConfPointCardBatch cardBatch = new ConfPointCardBatch();
                cardBatch.setCode(item);
                ConfPointCardBatch batch = mapper.selectByPrimaryCode(cardBatch);
                if (batch==null){
                    log.error("没有该部门，释放积分卡失败");
                    throw new AppRuntimeException("8888","释放失败");
                }
                //首先获取要释放积分卡的所有积分
                BigDecimal point = cardMapper.releasePointCartTotalPoint(item);
                if (point==null){
                    point = new BigDecimal(0);
                }
                //将积分卡释放
                Integer value = cardMapper.releasePointCart(item);

                String code = mapper.getPlatformCode(item);
                List<QuantityRequest> list = JSONObject.parseArray(batch.getQuantity(), QuantityRequest.class);
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setTotalNum(BigDecimal.ZERO);
                }
                Integer addPoint = confPlatformMapper.addPoint(code, point.add(batch.getLeftPoint()));
                if (addPoint > 0) {
                    ConfPointCardBatch confPointCardBatch = new ConfPointCardBatch();
                    confPointCardBatch.setCode(item);
                    confPointCardBatch.setQuantity(JSON.toJSON(list).toString());
                    Integer id = mapper.updateByPrimaryCode(confPointCardBatch);
                    if (id<1){
                        log.error("没有该部门，释放积分卡失败");
                        throw new AppRuntimeException("8888","释放失败");
                    }
                }
                return null;
            }).collect(Collectors.toList());
            log.error("释放积分结束，返回参数"+true);
            return 1;
        } else {
            log.error("释放积分结束，放回参数"+false);
            return 0;
        }
    }

    @Override
    public List<ConfPointCardBatchResponse> count() {
        List<ConfPointCardBatch> list=mapper.count();
        List<ConfPointCardBatchResponse> collect = list.stream().map(item -> {
            ConfPointCardBatchResponse response = new ConfPointCardBatchResponse();
            response.setSts(item.getSts());
            response.setType(item.getType());
            return response;
        }).collect(Collectors.toList());
        return collect;
    }


}
